package com.trkj.base;

import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

/**
 * 刷新数据时，实时响应服务器返回的数据改变
 * Created by LiZanhong on 2015/07/02.
 */
public class DataFilter {
    /**
     * 将oldData中的数据应用更改为newData对应的数据
     * @param oldData
     * @param newData
     */
    public static void applyChange(JSONArray oldData, JSONArray newData){
        if(newData == null || newData == null) return;
        Log.d("oldData.size", String.valueOf(oldData.size()));

        for(int i = 0; i < oldData.size(); i ++){
            for(int j = 0; j < newData.size(); j ++){
                String idName = getIdFieldName(oldData);
                if(idName == null) return;
                if(oldData.getJSONObject(i).getIntValue(idName)
                        == newData.getJSONObject(j).getIntValue(idName)){
                    JSONObject obj = newData.getJSONObject(i);
                    Set keys = obj.keySet();
                    for(Object key : keys){
                        obj.put(key.toString(), newData.getJSONObject(j).get(key));
                    }
                    break;
                }
            }
        }
        Log.d("oldData.size2", String.valueOf(oldData.size()));
    }

    /**
     * 根据id移除相同的元素
     * @param oldData
     * @param newData
     */
    public static void removeAllSame(JSONArray oldData, JSONArray newData){
        if(oldData == null || newData == null) return;

        for(int i = oldData.size() - 1; i >= 0; i --){
            for(int j = 0; j < newData.size(); j ++){
                String idName = getIdFieldName(oldData);
                if(idName == null) return;
                if(oldData.getJSONObject(i).getIntValue(idName)
                        == newData.getJSONObject(j).getIntValue(idName)){
                    oldData.remove(oldData.getJSONObject(i));
                    break;
                }
            }
        }
    }

    private static String getIdFieldName(JSONArray data){
        if(data == null || data.size() == 0) return null;

        for(int i = 0; i < data.size(); i ++){
            JSONObject o = data.getJSONObject(i);
            Set keys = o.keySet();
            for(Object key : keys){
                String s = key.toString();
                if(s.contains("id") || s.contains("ID")){
                    return s;
                }
            }
        }
        return null;
    }
}
